# -*- coding:utf-8 -*-
# @Author : mistchan
# @Time : 2022/8/31 0031 13:24
# @File : handle_win.py
# @Software: PyCharm

import sys
import win32gui
import win32con


def get_all_windows():
    hWnd_list = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWnd_list)

    return hWnd_list


def get_son_windows(parent):
    hWnd_child_list = []
    win32gui.EnumChildWindows(parent, lambda hWnd, param: param.append(hWnd), hWnd_child_list)

    return hWnd_child_list


def get_title(hwnd):
    title = win32gui.GetWindowText(hwnd)

    return title


def get_hwnd_from_name(name):
    hWnd_list = get_all_windows()

    for hwd in hWnd_list:
        title = get_title(hwd)
        if name in title:
            print(title)
            return hwd



# 使用win32gui.FindWindowEx找到目标文本框
def handle_windows(hwd, content):
    # 使用win32gui.FindWindowEx找到目标文本框
    tid = win32gui.FindWindowEx(hwd, None, 'Scintilla', None)
    len_ = win32gui.SendMessage(tid, win32con.WM_GETTEXTLENGTH) + 1  # 获取edit控件文本长度
    buffer = '0' * 50
    # 使用win32gui.SendMessage发送文本到目标文本框：
    print(win32gui.SendMessage(tid, win32con.WM_GETTEXT, len_, buffer))  # 读取文本
    # print(tid)



    # 可以继续找到下一个文本框：
    # input2 = win32gui.FindWindowEx(hwd, tid, 'Edit', None)


def key_return(tid):
    # 发送回车的方法：

    win32gui.PostMessage(tid, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32gui.PostMessage(tid, win32con.WM_KEYUP, win32con.VK_RETURN, 0)


if __name__ == '__main__':
    hwd = get_hwnd_from_name('Notepad')
    # print(hwd)
    # win32gui.SetWindowPos(hwd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
    #                       win32con.SWP_NOMOVE | win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER | win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE)
    # win32gui.SetForegroundWindow(hwd)
    # hwd = win32gui.FindWindow(None, '计算器')
    handle_windows(hwd, '11111')
